// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package meta

import (
	"fmt"
	"reflect"
)

var (
	// ErrValidate is an empty ValidateErr object, useful for type checking
	ErrValidate = &ValidateErr{}
)

// error types
const (
	TypeConflict = "conflict"
	TypeMismatch = "mismatch"
)

// ValidateErr is the error when meta validation fails with conflicts
type ValidateErr struct {
	Type   string // conflict type
	Target string // conflict Target
	Value  any    // conflict Value
	LHS    string // object 1
	RHS    string // object 2
}

// Error implements the error interface
func (e *ValidateErr) Error() string {
	return fmt.Sprintf("%s %s for '%v' between '%s' and '%s'", e.Target, e.Type, e.Value, e.LHS, e.RHS)
}

// Unwrap implements the error interface
func (e *ValidateErr) Unwrap() error { return nil }

// Is implements the error interface
func (e *ValidateErr) Is(target error) bool {
	t, ok := target.(*ValidateErr)
	if !ok {
		return false
	}

	// check for interface Value separately
	if e.Value != nil && t.Value != nil &&
		(!reflect.ValueOf(e.Value).IsValid() && !reflect.ValueOf(t.Value).IsValid()) {
		return false
	}
	// not supporting non-comparable values for now
	if e.Value != nil && t.Value != nil &&
		!(reflect.TypeOf(e.Value).Comparable() && reflect.TypeOf(t.Value).Comparable()) {
		return false
	}
	return (e.Type == t.Type || t.Type == "") &&
		(e.Target == t.Target || t.Target == "") &&
		(e.Value == t.Value || t.Value == nil || reflect.ValueOf(t.Value).IsZero()) &&
		(e.LHS == t.LHS || t.LHS == "") &&
		(e.RHS == t.RHS || t.RHS == "")
}
